package com.tuanzi.loan.business.service.settlementsystem.impl;

import com.tuanzi.loan.business.entity.settlementsystem.SettlementCompany;
import com.tuanzi.loan.business.entity.settlementsystem.SettlementPrepay;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementCompanyRepository;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementPrepayRepository;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementRemainRepository;
import com.tuanzi.loan.business.service.settlementsystem.BillStatus;
import com.tuanzi.loan.business.service.settlementsystem.SettlementPrepayService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.settlementsystem.SettlementPrepayRequest;
import com.tuanzi.loan.vo.response.settlementsystem.SettlementPrepayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author caiwanlin
 * @create 2018-08-22 17:39
 */
@Slf4j
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class SettlementPrepayServiceImpl extends BaseAuditServiceImpl<SettlementPrepay, Long> implements SettlementPrepayService {
    @Autowired
    private SettlementPrepayRepository settlementPrepayRepository;

    @Autowired
    private SettlementCompanyRepository settlementCompanyRepository;

    @Autowired
    private SettlementRemainRepository settlementRemainRepository;

    private ReentrantLock lock = new ReentrantLock();

    @Override
    protected JPAAuditRepository<SettlementPrepay, Long> getRepository() {
        return settlementPrepayRepository;
    }

    @Override
    public Page<SettlementPrepayResponse> list(PageSearcher<SettlementPrepayRequest> pageSearcher) {
        return settlementPrepayRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
    }

    @Override
    public void onSave(SettlementPrepay settlementPrepay,Long onSeeCompanyId) {
        Long settlementPrepayId = settlementPrepay.getId();


        //如果是添加，未开票状态
        if (settlementPrepayId == null) settlementPrepay.setBillStatus(BillStatus.NO_BILL.index);

        //更新公司的预付金额

        SettlementCompany company = null;
        Double settlementPrepayAmount = null;//充值金额
        Double companyPrepayAmount = null;
        Double lastPrepayAmount = settlementPrepay.getLastPrepayAmount();//最后一次预付金额
        try {
            lock.lock();//保证只有一个线程在执行更新操作
            company = settlementCompanyRepository.findOne(settlementPrepay.getCompanyId());
            companyPrepayAmount = company.getPrepayAmount();
            settlementPrepayAmount = settlementPrepay.getPrepayAmount();
            if (companyPrepayAmount == null){
                company.setPrepayAmount(settlementPrepayAmount);
            }
            else {
                log.info("收款记录公司ID，onSeeCompanyId="+onSeeCompanyId+",companyId="+settlementPrepay.getCompanyId());
                if (settlementPrepayId == null){ //如果是添加预付记录，公司的预付金额 = 原始预付金额+充值金额
                    log.info("收款记录添加预付记录：");
                    company.setPrepayAmount(companyPrepayAmount + settlementPrepayAmount);
                }
                else {//如果是修改预付记录 ， 公司的预付金额 = 原始预付金额 - 最后一次充值金额 + 要更新的充值金额
                    if (onSeeCompanyId.equals(settlementPrepay.getCompanyId())){//没有修改公司
//                        if (lastPrepayAmount != settlementPrepayAmount){
                            company.setPrepayAmount(companyPrepayAmount - lastPrepayAmount + settlementPrepayAmount);
//                        }
                        log.info(
                                String.format("收款记录不修改公司，companyPrepayAmount=%s,lastPrepayAmount=%s,settlementPrepayAmount=%s"
                                        ,companyPrepayAmount,lastPrepayAmount,settlementPrepayAmount));
                    }
                    else {//更改公司-预付金额的改变
                        log.info(
                                String.format("收款记录修改公司，companyPrepayAmount=%s,lastPrepayAmount=%s,settlementPrepayAmount=%s"
                                        ,companyPrepayAmount,lastPrepayAmount,settlementPrepayAmount));
                        SettlementCompany oldCompany = settlementCompanyRepository.findOne(onSeeCompanyId);
                        Double oldCompanyPrepayAmount = oldCompany.getPrepayAmount();
                        oldCompany.setPrepayAmount(oldCompanyPrepayAmount-lastPrepayAmount);
                        company.setPrepayAmount(companyPrepayAmount+settlementPrepayAmount);
                        settlementCompanyRepository.save(oldCompany);

                    }
                }
            }
            settlementCompanyRepository.save(company);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        //保存预付记录
        settlementPrepay.setLastPrepayAmount(settlementPrepayAmount);//设置最后一次更新金额
        settlementPrepayRepository.save(settlementPrepay);

        //插入余额记录
        /*SettlementRemain settlementRemain = null;
        if (settlementPrepayId == null){
            settlementRemain = new SettlementRemain();
            settlementRemain.setCompanyId(company.getId());
            settlementRemain.setCompanyName(company.getCompanyName());
            settlementRemain.setRemainType(RemainType.PREPAY.index);
            settlementRemain.setRelateId(settlementPrepay.getId());
            settlementRemain.setPrePrepayAmount(companyPrepayAmount==null?0:companyPrepayAmount);
            settlementRemain.setPrepayAmount(company.getPrepayAmount());
            settlementRemain.setPreExpendAmount(company.getExpendAmount());
            settlementRemain.setExpendAmount(company.getExpendAmount());
            settlementRemain.setPreRemainAmount(settlementRemain.getPrePrepayAmount()-settlementRemain.getPreExpendAmount());
            settlementRemain.setRemainAmount(settlementRemain.getPrepayAmount()-settlementRemain.getExpendAmount());
            settlementRemainRepository.save(settlementRemain);
        }
        else {
            if (lastPrepayAmount == settlementPrepayAmount) return;
            settlementRemain = settlementRemainRepository
                    .findSettlementRemainByRelateIdAndRemainType(settlementPrepayId,RemainType.PREPAY.index);
            Double oldPrePrepayAmount = settlementRemain.getPrePrepayAmount();
            Double oldPrepayAmount = settlementRemain.getPrepayAmount();
            //更新预付金额
//            settlementRemain.setPrePrepayAmount(oldPrePrepayAmount - lastPrepayAmount);
            settlementRemain.setPrepayAmount(oldPrepayAmount - lastPrepayAmount + settlementPrepayAmount);
            //更新剩余金额
            settlementRemain.setPreRemainAmount(settlementRemain.getPrePrepayAmount() - settlementRemain.getPreExpendAmount());
            settlementRemain.setRemainAmount(settlementRemain.getPrepayAmount() - settlementRemain.getExpendAmount());
            settlementRemainRepository.save(settlementRemain);
        }*/

    }

    @Override
    public List<SettlementPrepay> findAllByBillId(Long billId) {
        return settlementPrepayRepository.findAllByBillId(billId);
    }
}
